package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.commen.response.JsonResult;
import cn.tedu._05mvcboot03.commen.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.MvcUserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.MvcArticle;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Size;

/**
 * 用户控制类
 */
@Slf4j
@Api(tags = "用户文章模块")
@Validated
@RestController
@RequestMapping("/v1/users")
public class MvcUserController {
    @Autowired
    private MvcUserMapper mvcUserMapper;

    /**
     * 用户登录功能
     */
    @ApiOperation(value = "用户登录")
    @PostMapping(value = "/login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,
                            @ApiIgnore HttpSession session){
        //打桩
        log.debug(userLoginDTO.toString());
        //检验用户名和密码
        UserVO userVO = mvcUserMapper.selectUser(
                userLoginDTO.getUsername(),userLoginDTO.getPassword());
        if (userVO==null)
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        //用户登录
        session.setAttribute("user",userVO);
        return JsonResult.success();
    }

    /**
     * 发布文章功能
     */
    @ApiOperation(value = "发布文章")
    @PostMapping(value = "/article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO,
                              @ApiIgnore HttpSession session){
        //打桩
        log.debug(userArticleDTO.toString());
        //检验登录状态
        UserVO userVO = (UserVO) session.getAttribute("user");
//        if (userVO==null)
//            return new JsonResult(StatusCode.NOT_LOGIN);
        //发布文章
        MvcArticle mvcArticle = new MvcArticle();
        BeanUtils.copyProperties(userArticleDTO,mvcArticle);
        mvcArticle.setUserId(userVO.getId());
        mvcUserMapper.insertArticle(mvcArticle);
        return JsonResult.success();
    }

    /**
     * 查询指定文章功能
     */
    @ApiOperation(value = "查看指定文章")
    @ApiImplicitParam(name = "id",value = "文章编号",required = true,
    example = "1",dataType = "int")
    @GetMapping(value = "/selectByArticleId")
    public JsonResult selectByArticleId(
            @RequestParam @Range(min = 1,max = 100,message = "文章编号在1-100之间") int id){
        return JsonResult.success(mvcUserMapper.selectByArticleId(id));
    }
}
